<template>
  <div class="teach-info-view" v-loading="loading">
    <main class="table-wrapper table-container">
      <!-- <div style="height: 1000px; background-color: #cdcdcd;"></div> -->
      <div class="table-content">
        <el-table
          v-if="showTable"
          :data="tableList"
          stripe
          border
          header-cell-class-name="table-header"
          :cell-style="setCellStyle"
          class="responsive-table"
        >
          <el-table-column
            v-for="{ label, prop, width, fixed } in columnList"
            :key="prop"
            :label="label"
            :prop="prop"
            :width="width"
            align="center"
          >
            <template #default="scope">
              <span
                @click="toEditCell(scope.row, prop)"
                class="pointer"
                v-if="prop !== 'class_name'"
              >
                <template v-if="scope.row[prop] !== ''">
                  {{ scope.row[prop] }}
                </template>
                <span class="setting-btn" v-else> 设置 </span>
              </span>
              <span v-else>{{ scope.row[prop] }}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </main>
    <footer class="footer">
      <el-pagination
        background
        layout="total, prev, pager, next"
        :total="classTotal"
        @current-change="changePage"
        v-model:current-page="page"
      >
      </el-pagination>
    </footer>

    <SetTeacher
      v-if="showSetTeacher"
      :settingInfo="settingInfo"
      :gradeId="gradeId"
      @cancel="showSetTeacher = false"
      @update="setTeacherSuccess"
    />

    <EditTableView
      v-if="showBatchSetTeacher"
      :title="editTitle"
      :templatePath="templatePath"
      :schoolId="schoolId"
      :tableDataList="allTeachInfoList"
      :allUserList="allTeacherList"
      :uploadApi="$api.importEditTable"
      :sheetName="'任课信息'"
      :firstColumnOnlyOneUser="true"
      @cancel="showBatchSetTeacher = false"
      @update="batchSetTeacherSuccess"
    />
  </div>
</template>
<script>
import SetTeacher from './SetTeacher.vue';
import EditTableView from './EditTableView.vue';
import eventBus from '@/utils/eventBus';
import { mapGetters } from 'vuex';

export default {
  name: 'TeachInfoView',
  components: {
    SetTeacher,
    EditTableView,
  },
  props: {
    gradeId: { type: Number, required: true },
  },
  data() {
    return {
      loading: false,
      page: 1,
      teachInfoList: [],
      tableList: [],
      columnList: [],
      classTotal: 0,
      showTable: false,
      showSetTeacher: false,

      // 批量编辑相关
      showBatchSetTeacher: false,
      allTeachInfoList: [],
      allTeacherList: [],
      templatePath:
        'https://ebag-exam.oss-cn-shenzhen.aliyuncs.com/examination/teacher_sign/考务模版/阅卷系统单校版精准后台信息录入模板 (任课信息) .xlsx',
    };
  },
  computed: {
    ...mapGetters('school', ['schoolId']),
    editTitle() {
      const gradeName =
        this.$maps.gradeList.find((e) => e.id === this.gradeId)?.name || '';
      return gradeName + '-教学信息-在线批量编辑';
    },
  },
  watch: {
    gradeId() {
      this.getTeachInfoList();
    },
  },
  mounted() {
    this.getTeachInfoList();
    eventBus.$on('to-edit-teach-info', () => {
      this.toEditTable();
    });
  },
  beforeUnmount() {
    eventBus.$off('to-edit-teach-info');
  },
  methods: {
    async getTeachInfoList() {
      if (this.gradeId === 0) return;
      this.loading = true;
      try {
        const { F_data, F_responseNo, F_responseMsg } =
          await this.$api.getTeachInfoList({
            F_school_id: this.schoolId,
            F_grade: this.gradeId,
            F_page: this.page,
            F_limit: 10,
          });
        if (F_responseNo !== 10000) {
          this.$toast('获取教学信息失败：', F_responseMsg);
          this.teachInfoList = [];
        } else {
          const { total, class_infos } = F_data;
          this.classTotal = total;
          this.teachInfoList = class_infos || [];
          this.getTableList();
          this.getColumnList();
          this.showTable = false;
          this.$nextTick(() => {
            this.showTable = true;
          });
        }
      } catch (e) {
        console.error(e);
      }
      this.loading = false;
    },
    getTableList() {
      const teachList = [];
      this.teachInfoList.forEach(({ class_name, class_id, subject_infos }) => {
        const classItem = {
          class_id,
          class_name,
        };
        (subject_infos || []).forEach(({ subject_id, teacher_infos }) => {
          classItem['subject_' + subject_id] = (teacher_infos || [])
            .map((e) => e.TeacherName)
            .join('/');
        });
        teachList.push(classItem);
      });
      this.tableList = teachList;
    },
    getColumnList() {
      if (!this.teachInfoList.length) {
        this.columnList = [];
        return;
      }
      const subjectList = this.teachInfoList[0].subject_infos;
      const columnList = subjectList.map(({ subject_id, subject_name }) => {
        return {
          label: subject_name,
          prop: 'subject_' + subject_id,
          width: '180px',
        };
      });
      columnList.unshift({
        label: '班级',
        prop: 'class_name',
        width: '180px',
        fixed: true,
      });
      this.columnList = columnList;
    },

    changePage(val) {
      this.page = val;
      this.getTeachInfoList();
    },
    async toEditTable() {
      if (this.gradeId === 0) {
        this.$toast('请先选择年级');
        return;
      }
      this.loading = true;
      try {
        await this.getAllTeachInfoList();
        await this.getAllTeacherList();
        this.showBatchSetTeacher = true;
      } catch (error) {
        console.error('打开批量编辑失败:', error);
        this.$toast('打开批量编辑失败，请重试');
      } finally {
        this.loading = false;
      }
    },
    async getAllTeachInfoList() {
      try {
        const { F_data, F_responseNo, F_responseMsg } =
          await this.$api.getTeachInfoList({
            F_school_id: this.schoolId,
            F_grade: this.gradeId,
            F_page: 1,
            F_limit: 100,
          });
        if (F_responseNo !== 10000) {
          this.$toast('获取教学信息失败：', F_responseMsg);
          this.allTeachInfoList = [];
        } else {
          const { class_infos } = F_data;
          this.allTeachInfoList = class_infos.map(
            ({ class_id, class_name, subject_infos }) => ({
              id: class_id,
              name: class_name,
              sub_list: subject_infos.map(
                ({ subject_id, subject_name, teacher_infos }) => ({
                  sub_id: subject_id,
                  sub_name: subject_name,
                  user_list: (teacher_infos || []).map(
                    ({ TeacherId, TeacherName, Phone }) => ({
                      user_id: TeacherId,
                      user_name: TeacherName,
                      phone: Phone,
                    })
                  ),
                })
              ),
            })
          );
        }
      } catch (e) {
        console.error(e);
      }
    },
    async getAllTeacherList() {
      const { F_teachers } = await this.$api.getTeachers({
        F_page: 0,
        F_limit: 0,
        F_school_id: this.schoolId,
      });
      this.allTeacherList = (F_teachers || []).map(
        ({ F_teacher: { F_id, F_name } }) => ({
          id: F_id,
          name: F_name,
        })
      );
    },
    toEditCell(row, prop) {
      const { class_id, class_name, subject_infos } = this.teachInfoList.find(
        (e) => e.class_id === row.class_id
      );
      const subjectId = Number(prop.split('_')[1]);
      const subjectItem = subject_infos.find((e) => e.subject_id === subjectId);
      this.settingInfo = {
        class_id,
        class_name,
        ...subjectItem,
      };
      this.showSetTeacher = true;
    },
    setTeacherSuccess() {
      this.showSetTeacher = false;
      this.getTeachInfoList();
    },
    batchSetTeacherSuccess() {
      this.showBatchSetTeacher = false;
      this.getTeachInfoList();
    },
    setCellStyle({ rowIndex, columnIndex }) {
      if (columnIndex === 0) {
        // 第一列
        return { backgroundColor: 'rgba(0, 156, 255, 0.06)' }; // 设置背景颜色
      }
      return {};
    },
  },
};
</script>
<style lang="less" scoped>
.teach-info-view {
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow-y: auto;
  .table-wrapper {
    flex: 1;
    overflow-y: auto;
  }

  .footer {
    height: 50px;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  :deep(.el-table) {
    .pointer {
      cursor: pointer;
    }
    .setting-btn {
      color: #009cff;
      cursor: pointer;
    }
  }
}
</style>
